import { Component, EventEmitter, OnInit, Output } from '@angular/core';

import { Day } from './day'

import * as moment from 'moment';

@Component({
  selector: 'calendar',
  templateUrl: "./calendar.component.html",
  styleUrls: [ "./calendar.component.css" ]
})
export class CalendarComponent implements OnInit {
  calendar: any
  showDate: Day
  days: Array<Day>
  tmp_day: Day
  @Output() onSelected = new EventEmitter<Array<Day>>()

  constructor() { }

  ngOnInit(): void {
     moment.locale('en', {
      weekdays : [
          "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"
      ]
    });
    this.setCalendar(moment())
    this.changeShowDate(this.calendar.today)
  }

  changeShowDate(day: Day) {
    this.showDate = day
    this.onSelected.emit([ day ])
  }

  setCalendar(curr: any): void {
    var year = curr.year(), month = curr.month();
    var argv = new Array()
    var tmp_month = month + 1
    if(tmp_month < 10) tmp_month = '0'+ tmp_month
    argv['date'] = year + '-' + tmp_month 
    console.log(argv) 
    var data = new Array()
    argv["token"] = localStorage.getItem("token")
    var url = "/api/bigdata/pm/dev/tasks/list.json" + '?token=' + argv["token"] +'&date=' + argv["date"];
    let xhr: XMLHttpRequest = new XMLHttpRequest();
    xhr.open('GET', url, false)
    xhr.send()

    if (xhr.readyState == 4){
      this.days = JSON.parse(xhr.responseText).data
    }

    var cal = { weeks: [ ], mom: null, today: null, curr: null, title: null },
        weeks = { }, days = [ ]
    cal.mom = moment().year(year).month(month);
    cal.today = { num: moment().date(), m: moment().month(), y: moment().year(),
                  date: moment().format("YYYY-MM-DD") }
    cal.curr = { num: curr.date(), m: curr.month() }
    cal.title = cal.mom.format("YYYY年MM月DD日dddd")
    var mom = moment().year(year).month(month - 1).date(20)
    for (var i = 1; i < 60; i++) {
      mom.add(1, "day");
      var week = mom.week();
      if (!weeks[week]) weeks[week] = Array(7);
      var day = { num: mom.date(), m: mom.month(), y: mom.year(), state: null }
      var str_day = mom.format('YYYY-MM-DD')
      this.days.map(t_day => {
        if (t_day.date == str_day){
          if (t_day.avg > 12 && t_day.avg < 20 )
            day.state = 'green'
          if (t_day.avg > 20)
            day.state = 'red'
          if (t_day.avg < 12)
            day.state = 'yellow'
        }
      })
      weeks[week][mom.weekday()] = day;
      days.push(mom)
    }
    Object.keys(weeks).map(wNum => {
      cal.weeks.push({ days: weeks[wNum], num: wNum }) })
    cal.weeks = cal.weeks.filter(week => {
      for (var i = 0; i < 7; i++) {
        if (!week.days[i]) return false;
        if (week.days[i].m == month) return true;
      }
      return false;
    })
    this.calendar = cal
  }

  calPrev(): void {
    this.setCalendar(this.calendar.mom.subtract(1, "month"));
  }

  calNext(): void {
    this.setCalendar(this.calendar.mom.add(1, "month"));
  }

  calToday() {
    this.setCalendar(moment());
  }
}
